package com.jeeplus.modules.api.utils;


import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.*;


/**
 * AES加密
 *
 */
public class AESUtil {
    public static final AESUtil instance = new AESUtil();
    public static boolean initialized = false;  
	
	/**
	 * AES解密
	 * @param content 密文
	 * @return
	 * @throws InvalidAlgorithmParameterException 
	 * @throws NoSuchProviderException 
	 */
	public byte[] decrypt(byte[] content, byte[] keyByte, byte[] ivByte) throws InvalidAlgorithmParameterException {
		initialize();
		try {
		        /*// 如果密钥不足16位，那么就补足.  这个if 中的内容很重要
		        int base = 16;
		        if (keyByte.length % base != 0) {
		            int groups = keyByte.length / base + (keyByte.length % base != 0 ? 1 : 0);
		            byte[] temp = new byte[groups * base];
		            Arrays.fill(temp, (byte) 0
		            );
		            System.arraycopy(keyByte, 0, temp, 0, keyByte.length);
		            keyByte = temp;
		        }*/
			Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
//			Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
			Key sKeySpec = new SecretKeySpec(keyByte, "AES");
			cipher.init(Cipher.DECRYPT_MODE, sKeySpec, generateIV(ivByte));// 初始化 
			return cipher.doFinal(content);
		}  // TODO Auto-generated catch block
		catch (Exception e) {
			e.printStackTrace();
		}// TODO Auto-generated catch block

		return null;
	}  
	
	public static void initialize(){  
        if (initialized) return;  
        Security.addProvider(new BouncyCastleProvider());
        initialized = true;  
    }
	//生成iv  
    public static AlgorithmParameters generateIV(byte[] iv) throws Exception{  
        AlgorithmParameters params = AlgorithmParameters.getInstance("AES");  
        params.init(new IvParameterSpec(iv));  
        return params;  
    }  
}